package cn.jiadakeji.parent.service.impl;

import cn.jiadakeji.parent.common.constant.RedisPrefixConstants;
import cn.jiadakeji.parent.domain.School;
import cn.jiadakeji.parent.dto.SchoolDTO;
import cn.jiadakeji.parent.mapper.SchoolMapper;
import cn.jiadakeji.parent.service.SchoolService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author heyanfeng
 * @create 2022-03-09 16:50
 */
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public List<SchoolDTO> getSchoolList() {
        // TODO:考虑缓存问题
        // 先从缓存中获取
        String data = redisTemplate.opsForValue().get(RedisPrefixConstants.SCHOOL_PREFIX);
        if (data != null) {
            return JSON.parseObject(data, new TypeReference<List<SchoolDTO>>() {});
        } else {
            List<School> schoolList = baseMapper.selectList(null);
            // 类型转换
            List<SchoolDTO> collect = schoolList.stream().map(school -> {
                SchoolDTO schoolDTO = new SchoolDTO();
                BeanUtils.copyProperties(school, schoolDTO);
                return schoolDTO;
            }).collect(Collectors.toList());
            String jsonString = JSON.toJSONString(collect);
            redisTemplate.opsForValue().set(RedisPrefixConstants.SCHOOL_PREFIX, jsonString);
            return collect;
        }
    }

}
